<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>测试接口</title>
</head>

<body>
    <h1>测试接口</h1>
    <p>
        <button id="login">登录</button>
    </p>
    <p>
        <button id="userInfo">获取用户信息</button>
        <button id="userAllInfo">获取所有用户信息</button>
    </p>
    <p>
        <button id="logout">退出登录</button>
    </p>

    <script>
        const baseUrl = "http://localhost:3000";
        // 登录
        document.querySelector("#login").onclick = async () => {
            const result = await fetch("/users/login", {
                method: "post",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    username: "张三",
                    password: "123456",
                }),
            }).then((r) => r.json());
            const t = result.data.token;
            localStorage.setItem("token", t);
            console.log(result);
        };
        // 获取用户信息
        const getUserInfo = async (isAll = false) => {
            const token = localStorage.getItem("token");
            if (!token) {
                alert("请先登录");
                return;
            }
            _allPath = isAll ? "/666" : "";
            const result = await fetch("/users/userInfo" + _allPath, {
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: "Bearer " + token,
                },
                body: JSON.stringify({}),
            }).then((r) => r.json());
            console.log(result);
        };
        document.querySelector("#userInfo").onclick = () => getUserInfo();
        document.querySelector("#userAllInfo").onclick = () => getUserInfo(true);
        // 退出登录
        document.querySelector("#logout").onclick = async () => {
            const token = localStorage.getItem("token");
            if (!token) {
                alert("请先登录");
                return;
            }
            const result = await fetch("/users/logout", {
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: "Bearer " + token,
                },
                body: JSON.stringify({}),
            }).then((r) => r.json());
            console.log(result);
        };
    </script>
</body>

</html>